#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>

#define PORT 12345
#define GROUP_IP "239.255.0.1"

int main(int argc, char const *argv[])
{
    //创建UDP套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd == -1)
    {
        perror("socket创建失败：");
        return -1;
    }

    //配置组播目标地址
    struct sockaddr_in group_addr;
    memset(&group_addr, 0, sizeof(group_addr));
    group_addr.sin_family = AF_INET;
    group_addr.sin_port = htons(PORT);
    group_addr.sin_addr.s_addr = inet_addr(GROUP_IP);

    //设置组播包的TTL（TTL -> Time To Live）
    int ttl = 1; //TTL值设为1，表示数据包仅在本地网络中传播
    int ret_set = setsockopt(sockfd, IPPROTO_IP, IP_MULTICAST_TTL, &ttl, sizeof(ttl));
    if (ret_set == -1){
        perror("加入组播失败：");
        close(sockfd);
        return -1;
    }

    //发送数据到组播组
    char message[] = "Hello, Multicast Group!";
    ssize_t ret_send = sendto(sockfd, message, sizeof(message), 0, (struct sockaddr *)&group_addr, sizeof(group_addr));
    if (ret_send == -1){
        perror("发送数据失败：");
    }else{
        printf("发送数据成功：%s:%zd bytes\n", message, ret_send);
    }

    return 0;
}
